package com.ruoyi.system;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class MyDemo {

    /**
     * 获取对象的泛型
     *
     * @param src   待获取泛型对象
     * @param index 泛型的位置
     * @param <T>   泛型
     * @return 泛型Class类
     */
    public static <T> Class getInstance(Object src, int index) {
        if (src == null || index < 0) {
            return null;
        }
        Class aClass = src.getClass();
        Type gSuperclass = aClass.getGenericSuperclass();
        if (gSuperclass instanceof ParameterizedType) {
            try {
                ParameterizedType pType = (ParameterizedType) gSuperclass;
                Type[] types = pType.getActualTypeArguments();
                if (index < types.length) {
                    Class desClass = (Class<T>) types[index];
                    return desClass;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
//        Person<String> person1 = new Person<String>();
        Person<String> person1 = new Person<String>() {
        };
        //就一个泛型 故获取0位 即可。
        Class instance1 = getInstance(person1, 0);
        System.out.println("instance_1 = " + instance1);

        Fruit<Integer, Float, Long> fruit = new Fruit<Integer, Float, Long>() {
        };
        Class fInstance0 = getInstance(fruit, 0);
        Class fInstance1 = getInstance(fruit, 1);
        Class fInstance2 = getInstance(fruit, 2);
        System.out.println("\nfInstance0 = " + fInstance0
                + "\nfInstance1 = " + fInstance1
                + "\nfInstance2 = " + fInstance2);

        printLn(Person.class);
        printLn(Programmer.class);
    }

    private static void printLn(Class clazz) {
        String name = clazz.getSimpleName();
        Class superClz = clazz.getSuperclass();
        Type genericClz = clazz.getGenericSuperclass();
        System.out.println("\n" + name + "\n getSuperclass() = " + superClz + "\n getGenericSuperclass() = " + genericClz);
    }

    public static class Fruit<T, P, D> {
        private T time;
        private P price;
        private D distance;
    }

    public static class Person<T> {
        private T data;
    }

    public static class Programmer extends Person<String> {
    }

}
